package kz.kstu.scantest.app.util.locator.factory;

import kz.kstu.scantest.app.util.locator.EJBLocalServiceLocator;
import kz.kstu.scantest.app.util.locator.EJBRemoteServiceLocator;
import kz.kstu.scantest.app.util.locator.ServiceLocator;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Filipp_Stankevich
 *         created: 8/5/11 2:40 PM
 */
public class ServiceLocatorFactory {

    private static final Map<String, ServiceLocator> SERVICE_LOCATOR_CACHE = new HashMap<String, ServiceLocator>();

    public static ServiceLocator getServiceLocator(boolean isOnline) {
        String className = isOnline ? EJBRemoteServiceLocator.class.getName():
                EJBLocalServiceLocator.class.getName();
        ServiceLocator serviceLocator;
        if (SERVICE_LOCATOR_CACHE.containsKey(className)) {
            serviceLocator = SERVICE_LOCATOR_CACHE.get(className);
        } else {
            try {
                Class<ServiceLocator> serviceClass = (Class<ServiceLocator>) Class.forName(className);
                serviceLocator = serviceClass.newInstance();
                SERVICE_LOCATOR_CACHE.put(className, serviceLocator);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Error during getting service locator: " + className, e);
            } catch (InstantiationException e) {
                throw new IllegalArgumentException("Error during getting instance of service locator: " + className, e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException("Error during getting instance of service locator: " + className, e);
            }
        }
        return serviceLocator;
    }
}
